<?php

require_once ('lib/OAuth.php');

class YelpAPIHandler {

    // property declaration
    public $term;
    public $location;
    public $response;
    
    const consumer_key = "xvnnlynuheOMeOcCr-3vYA";
    const consumer_secret = "c3PEm4Z1JJ1p7wbySrQM4XgfUEA";
    const token = "g5-bqy_svimWhCJSinU6CpbCPWGgOpTj";
    const token_secret = "NOp-hBQeOTj1CzqXiun-j0i1kLM";

    public function __construct($term, $location) {
        $this->term = $term;
        $this->location = $location;
    }

    public function connect() {
        
        // For examaple, search for 'tacos' in 'sf'
        $unsigned_url = "http://api.yelp.com/v2/search?" .
                "term=" . $this->term . 
                "&limit=3" .
                "&location=" . $this->location . 
                "&sort=2" . 
                "&category_filter=restaurants";

        // Token object built using the OAuth library
        $token = new OAuthToken(self::token, self::token_secret);

        // Consumer object built using the OAuth library
        $consumer = new OAuthConsumer(self::consumer_key, self::consumer_secret);

        // Yelp uses HMAC SHA1 encoding
        $signature_method = new OAuthSignatureMethod_HMAC_SHA1();

        // Build OAuth Request using the OAuth PHP library. Uses the consumer and token object created above.
        $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_url);

        // Sign the request
        $oauthrequest->sign_request($signature_method, $consumer, $token);

        // Get the signed URL
        $signed_url = $oauthrequest->to_url();

        // Send Yelp API Call
        $ch = curl_init($signed_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $data = curl_exec($ch); // Yelp response
        curl_close($ch);

        // Handle Yelp response data
        $response = json_decode($data);
        $this->response = $response;
    }

}

?>
